package com.tyylab.kestrel.framework.spring.rpc.feign.impl;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.Set;

public class FeignClientConfigGenerator {
    Map<String, Set<String>> servicePackeageMap = Maps.newConcurrentMap();
    Map<String, String> packageServiceMap = Maps.newConcurrentMap();

    public FeignClientConfigGenerator(Map<String, Set<String>> servicePackeageMap) {
        this.servicePackeageMap = servicePackeageMap;

        for (Map.Entry<String, Set<String>> entry : servicePackeageMap.entrySet()) {
            for(String packageName : entry.getValue()) {
                packageServiceMap.put(packageName, entry.getKey());
            }
        }

//        for (String key : servicePackeageMap.keySet()) {
//            for(String packageName : servicePackeageMap.get(key)) {
//                packageServiceMap.put(packageName, key);
//            }
//        }
    }

    public String getFeignClientName(Class<?> api) {
        String packageName = api.getPackage().getName();
        if (packageServiceMap.containsKey(packageName)) {
            return packageServiceMap.get(packageName);
        }
        else{
            int maxLength = -1;
            String serviceName = "";
            for (String servicePackage : servicePackeageMap.keySet()) {
                if (packageName.startsWith(servicePackage) && servicePackage.length() > maxLength) {
                    maxLength = servicePackage.length();
                    serviceName = packageServiceMap.get(servicePackage);
                }
            }

            if (maxLength > 0){
                return serviceName;
            }
            else{
                return null;
            }
        }
    }

    public String getFeignClientPath(Class<?> api) {
        return api.getSimpleName() + "/";
    }
}
